package com.spit.tph.nike_mvp.ui

import CONSUMABLES_RECEIVE
import CONSUMABLES_RESTOCK
import CONSUMABLES_WAREHOUSE
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatCheckBox
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.csl.ams.nike_mvp.recyclerview.DpUtils
import com.csl.ams.nike_mvp.recyclerview.SpaceItemDecoration
import com.csl.ams.nike_mvp.utils.PopupWindowTool
import com.google.zxing.integration.android.IntentIntegrator
import com.spit.tph.MainActivity
import com.spit.tph.R
import com.spit.tph.SystemFragment.BaseFragment
import com.spit.tph.nike_mvp.adapter.ConsumablesAdapter
import com.spit.tph.nike_mvp.impl.ConsumablesContract
import com.spit.tph.nike_mvp.presenter.ConsumablesPresenter
import com.spit.tph.nike_mvp.recyclerview.AutoSwipeRefreshView
import com.yyc.stocktake.bean.DataBean
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Collections

/**
 * User: Nike
 *  2024/2/23 17:20
 *      消耗品
 */
class ConsumablesFrg : BaseFragment(), ConsumablesContract.View, OnClickListener,
    MainActivity.OnActivityResultListener1, MainActivity.OnListUpdateListener {

    val mPresenter by lazy { ConsumablesPresenter() }

    val listBean = ArrayList<DataBean>()

    val adapter by lazy { ConsumablesAdapter(requireContext(), listBean) }

    var mEdittext: EditText? = null
    var mLayout: LinearLayout? = null
    var mCbText: AppCompatCheckBox? = null

    var mSwipeRefresh: AutoSwipeRefreshView? = null
    var mRecyclerView: RecyclerView? = null

    var isAllSelect: Boolean = false // 是否打开了多选框

    var mCStatus = -1//选中状态

    var isCheckBoxChecked: Boolean = false

    var isCreated = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.f_consumables, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mPresenter.init(this)
        this.view = view
        view.findViewById<View>(R.id.back).visibility = View.INVISIBLE

        val title = when (mCStatus) {
            CONSUMABLES_RECEIVE -> requireActivity().getString(R.string.receive1)
            CONSUMABLES_WAREHOUSE -> requireActivity().getString(R.string.warehouse)
            CONSUMABLES_RESTOCK -> requireActivity().getString(R.string.restock)
            else -> ""
        }
        (view.findViewById<View>(R.id.toolbar_title) as TextView).text =
            getString(R.string.consumables) + " " + title

        view.findViewById<View>(R.id.menu).setOnClickListener {
            (activity as MainActivity?)!!.updateDrawerStatus()
            (activity as MainActivity?)!!.mDrawerLayout.openDrawer(Gravity.RIGHT)
        }
        mEdittext = view.findViewById(R.id.edittext)
        val add = view.findViewById<ImageView>(R.id.add)
        add.background = ContextCompat.getDrawable(requireContext(), R.drawable.icon_4)
        add.setOnClickListener(this)
        add.visibility = View.GONE
        view.findViewById<ImageView>(R.id.scan).setOnClickListener(this)
        (activity as MainActivity).setOnActivityResultListener1(this)
        (activity as MainActivity).setOnListUpdateListener(this)

        mLayout = view.findViewById(R.id.layout)
        mCbText = view.findViewById(R.id.cb_text)
        view.findViewById<AppCompatTextView>(R.id.bt_receive).setOnClickListener(this)
        view.findViewById<AppCompatTextView>(R.id.bt_warehouse).setOnClickListener(this)
        view.findViewById<AppCompatTextView>(R.id.bt_restock).setOnClickListener(this)
        view.findViewById<View>(R.id.fy_close).setOnClickListener(this)
        mRecyclerView = view.findViewById(R.id.recyclerView)
        mSwipeRefresh = view.findViewById(R.id.swipeRefresh)

        mRecyclerView?.setLayoutManager(LinearLayoutManager(context));
        mRecyclerView?.addItemDecoration(SpaceItemDecoration(DpUtils.dip2px(requireContext(),10f), DpUtils.dip2px(requireContext(),10f)))
        mRecyclerView?.setHasFixedSize(true)
        mRecyclerView?.setNestedScrollingEnabled(true)
        mRecyclerView?.adapter = adapter
        if (!isCreated){
            mSwipeRefresh?.post({
                mSwipeRefresh?.autoRefresh()
            })
            isCreated = true
        }

        mSwipeRefresh?.setOnRefreshListener {
            mPresenter.onListRequest()
        }
        adapter?.run {
            setOnItemClickListener(object : ConsumablesAdapter.OnItemClickListener {
                override fun onItemClick(position: Int, item: DataBean, view: View) {
                    if (isAllSelect) {
                        updateSelectStatus(position)
                    } else {
                        /*if (mCStatus == -1){
                            showPowStatus()
                            return
                        }
                        val bean = adapter.mFilterList[position]
                        var list = ArrayList<DataBean>()
                        bean.status = 1
                        list.add(bean)
                        mPresenter.toConsumablesDescFrg(list, activity, mCStatus)*/
                    }
                }
            })
            setOnItemLongClickListener(object : ConsumablesAdapter.OnItemLongClickListener {
                override fun onItemClick(position: Int, item: DataBean, view: View) {
                    if (!isAllSelect) {
                        updateSelectStatus(position)
                    }
                    mRecyclerView?.scrollToPosition(position)
                }
            })
        }

        mEdittext?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                adapter?.filter?.filter(p0)
//                onCloseChexb()
            }

            override fun afterTextChanged(p0: Editable?) {

            }
        })

        mCbText?.setOnClickListener {
            isCheckBoxChecked = !isCheckBoxChecked
            mCbText?.isChecked = isCheckBoxChecked

            val newStatus = if (isCheckBoxChecked) 1 else 0
            /*adapter.mFilterList.forEach { bean ->
                bean.status = newStatus
            }*/
            listBean.forEach { it.status = newStatus }
            adapter.appendList(listBean)
            mEdittext?.setText("")
            adapter.notifyDataSetChanged()
            setSelectAllNumber()
        }
    }

    private fun showPowStatus() {
        val tool = PopupWindowTool(requireActivity())
        tool.showConsumablesStatus()
        tool.setOnClickListener1(object : PopupWindowTool.OnClickListener1 {
            override fun onStatus(i: Int) {
                mCStatus = i
                val title = when (mCStatus) {
                    CONSUMABLES_RECEIVE -> requireActivity().getString(R.string.receive1)
                    CONSUMABLES_WAREHOUSE -> requireActivity().getString(R.string.warehouse)
                    CONSUMABLES_RESTOCK -> requireActivity().getString(R.string.restock)
                    else -> ""
                }
                (view.findViewById<View>(R.id.toolbar_title) as TextView).text =
                    getString(R.string.consumables) + " " + title
            }
        })
    }

    private fun updateSelectStatus(position: Int) {
        val bean = adapter.mFilterList[position]
        bean.status = if (bean.status == 1) 0 else 1
        adapter.notifyItemChanged(position, bean)
        onAllSelect(bean.status)
    }

    private fun onAllSelect(status: Int) {
        if (status == 0) {
//            val isAllStatusZero = adapter.mFilterList.all { bean -> bean.status == 0 }
            val isAllStatusZero = listBean.all { it.status == 0 }
            mLayout?.visibility = if (isAllStatusZero) View.GONE else View.VISIBLE
        } else {
            mLayout?.visibility = if (mLayout?.visibility == View.GONE) View.VISIBLE else mLayout?.visibility!!
        }
        isAllSelect = mLayout?.visibility != View.GONE
        setSelectAllNumber()
    }

    private fun setSelectAllNumber() {
//        val countStatusOne = adapter.mFilterList.count { it.status == 1 }
        val countStatusOne = listBean.count { it.status == 1 }
        mCbText?.text = " ${getString(R.string.select_all)} $countStatusOne )"

//        val isAllSelected = countStatusOne == adapter.mFilterList.size
        val isAllSelected = countStatusOne == listBean.size
        mCbText?.isChecked = isAllSelected
        isCheckBoxChecked = isAllSelected
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.scan -> {
                mPresenter.toZking(activity)
            }
            R.id.add -> {
                showPowStatus()
            }
            R.id.bt_receive -> {
                mPresenter.toConsumablesDescFrg(listBean.filter { it.status == 1 } as ArrayList<DataBean>, activity, mCStatus = CONSUMABLES_RECEIVE)
                onCloseChexb()
            }
            R.id.bt_warehouse ->{
                mPresenter.toConsumablesDescFrg(listBean.filter { it.status == 1 } as ArrayList<DataBean>, activity, mCStatus = CONSUMABLES_WAREHOUSE)
                onCloseChexb()
            }
            R.id.bt_restock ->{
                mPresenter.toConsumablesDescFrg(listBean.filter { it.status == 1 } as ArrayList<DataBean>, activity, mCStatus = CONSUMABLES_RESTOCK)
                onCloseChexb()
            }
            R.id.fy_close -> {
                onCloseChexb()
            }
        }
    }

    private fun onCloseChexb() {
        isAllSelect = false
        listBean.forEach { it.status = 0 }
        adapter.appendList(listBean)
        adapter.notifyDataSetChanged()
        mLayout?.visibility = View.GONE
        mEdittext?.setText("")
    }

    override fun setListCallback(list: ArrayList<DataBean>) {
        mSwipeRefresh?.isRefreshing = false
        listBean.clear()
        listBean.addAll(list)
        adapter?.appendList(list)
        adapter?.notifyDataSetChanged()
        onCloseChexb()
    }

    override fun setMedicalTeamListCallback(list: java.util.ArrayList<DataBean>) {
        TODO("Not yet implemented")
    }

    override fun setWarehouseListCallback(list: java.util.ArrayList<DataBean>) {
        TODO("Not yet implemented")
    }

    override fun setMaterialListCallback(list: java.util.ArrayList<DataBean>) {
        TODO("Not yet implemented")
    }

    override fun setNoData() {
        mSwipeRefresh?.isRefreshing = false
    }

    override fun setTherapistsListCallback(dataBeans: java.util.ArrayList<DataBean>) {
        TODO("Not yet implemented")
    }

    override fun onResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        var contents = result.contents
        if (contents != null){
            mEdittext?.setText(contents)
        }
        /*var index = adapter.mFilterList.indexOfFirst { bean ->
            (bean.consumablesNo.equals(contents, ignoreCase = true) == true)
        }
        if (index != -1) {
            Handler().postDelayed({
                var list = ArrayList<DataBean>()
                list.add(adapter.mFilterList[index])
                mPresenter.toConsumablesDescFrg(list, activity, mCStatus)
            }, 1000)
        }*/
    }

    override fun onUpdateList(list: List<DataBean>?) {
        mPresenter.onListRequest()
    }

}